<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="自习室" prop="roomId">
        <el-select
          v-model="queryParams.roomId"
          placeholder="请选择自习室"
          clearable
          filterable
          @focus="loadRoomOptions"
        >
          <el-option
            v-for="item in roomOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预约日期" prop="reservationDate">
        <el-date-picker
          v-model="queryParams.reservationDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择日期"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:reservation:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="reservationList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column
        label="预约人"
        align="center"
        prop="userName"
        width="120"
      />
      <el-table-column
        label="自习室"
        align="center"
        prop="roomName"
        width="150"
      />
      <el-table-column
        label="座位编号"
        align="center"
        prop="seatNumber"
        width="120"
      />
      <el-table-column
        label="预约日期"
        align="center"
        prop="reservationDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reservationDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="时间段"
        align="center"
        prop="timeSlot"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ formatTimeSlot(scope.row.timeSlot) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="120">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ formatStatus(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="申请时间"
        align="center"
        prop="applyTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applyTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:reservation:edit']"
            v-if="scope.row.status === 0"
            >审核</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:reservation:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 审核对话框 -->
    <el-dialog
      title="审核预约"
      :visible.sync="reviewOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="reviewForm"
        :model="reviewForm"
        :rules="reviewRules"
        label-width="80px"
      >
        <el-form-item label="预约人" prop="userName">
          <el-input v-model="reviewForm.userName" :disabled="true" />
        </el-form-item>
        <el-form-item label="自习室" prop="roomName">
          <el-input v-model="reviewForm.roomName" :disabled="true" />
        </el-form-item>
        <el-form-item label="座位号" prop="seatNumber">
          <el-input v-model="reviewForm.seatNumber" :disabled="true" />
        </el-form-item>
        <el-form-item label="审核结果" prop="approved">
          <el-radio-group v-model="reviewForm.approved">
            <el-radio :label="true">通过</el-radio>
            <el-radio :label="false">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="reason">
          <el-input
            v-model="reviewForm.reason"
            type="textarea"
            placeholder="请输入审核备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitReview">确 定</el-button>
        <el-button @click="reviewOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getReservationListAPI,
  getReservationInfoAPI,
  deleteReservationAPI,
  reviewReservationAPI,
} from "@/api/reservation/record";
import { getRoomListAPI, getRoomInfoAPI } from "@/api/resource/room";
import { getSeatInfoAPI } from "@/api/resource/seat";
import { getUser } from "@/api/system/user";
export default {
  name: "Reservation",
  data() {
    return {
      // 状态选项
      statusOptions: [
        { value: 0, label: "待审核" },
        { value: 1, label: "已取消" },
        { value: 2, label: "已拒绝" },
        { value: 3, label: "待签到" },
        { value: 4, label: "已签到" },
        { value: 5, label: "未签到" },
      ],
      // 自习室选项
      roomOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预约表格数据
      reservationList: [],
      // 是否显示审核弹出层
      reviewOpen: false,
      // 审核表单
      reviewForm: {
        id: null,
        userName: "",
        roomName: "",
        seatNumber: "",
        approved: true,
        reason: "",
      },
      // 审核表单校验
      reviewRules: {
        approved: [
          { required: true, message: "请选择审核结果", trigger: "blur" },
        ],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roomId: undefined,
        seatNumber: undefined,
        userName: undefined,
        status: undefined,
        reservationDate: undefined,
      },
    };
  },
  created() {
    this.getList();
    this.loadRoomOptions();
  },
  methods: {
    // 格式化时间段
    formatTimeSlot(slot) {
      const map = { 1: "上午", 2: "下午", 3: "晚上" };
      return map[slot] || "未知";
    },
    // 格式化状态
    formatStatus(status) {
      const map = {
        0: "待审核",
        1: "已取消",
        2: "已拒绝",
        3: "待签到",
        4: "已签到",
        5: "未签到",
      };
      return map[status] || "未知";
    },
    // 获取状态标签类型
    getStatusTagType(status) {
      const map = {
        0: "warning",
        1: "info",
        2: "danger",
        3: "warning",
        4: "success",
        5: "danger",
      };
      return map[status] || "";
    },
    /** 加载自习室选项 */
    async loadRoomOptions() {
      try {
        const response = await getRoomListAPI({ pageNum: 1, pageSize: 1000 });
        if (response.code === 200) {
          this.roomOptions = response.rows;
        } else {
          this.$message.error(
            "加载自习室列表失败: " + (response.msg || "未知错误")
          );
        }
      } catch (error) {
        this.$message.error("加载自习室列表出错: " + error.message);
      }
    },
    /** 查询预约列表 */
    async getList() {
      this.loading = true;
      try {
        // 1. 拉取所有预约数据（pageSize 给一个足够大值）
        const res = await getReservationListAPI({
          ...this.queryParams,
          pageNum: 1,
          pageSize: 10000, // 你预估的最大数据量
        });

        // 2. 添加详细信息
        const detailedList = await this.enrichReservationData(res.rows);

        // 3. 前端根据预约日期过滤
        const filteredList = detailedList.filter((item) => {
          if (!this.queryParams.reservationDate) return true;
          const itemDate = this.parseTime(item.reservationDate, "{y}-{m}-{d}");
          return itemDate === this.queryParams.reservationDate;
        });

        // 4. 再前端分页（模拟分页）
        const start =
          (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
        const end = start + this.queryParams.pageSize;
        this.reservationList = filteredList.slice(start, end);
        this.total = filteredList.length;
      } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error("获取数据失败");
      } finally {
        this.loading = false;
      }
    },

    /** 丰富预约数据，添加关联信息 */
    async enrichReservationData(reservations) {
      // 使用Promise.all并行获取所有关联信息
      return Promise.all(
        reservations.map(async (item) => {
          try {
            // 并行获取自习室和座位信息
            const [roomRes, seatRes, userRes] = await Promise.all([
              getRoomInfoAPI(item.roomId).catch(() => ({ data: {} })),
              getSeatInfoAPI(item.seatId).catch(() => ({ data: {} })),
              getUser(item.userId).catch(() => ({ data: {} })),
            ]);

            return {
              ...item,
              roomName: roomRes.data?.name || "未知自习室",
              seatNumber: seatRes.data?.number || "未知座位",
              userName: userRes.data?.userName || "未知用户",
              // 如果还需要其他字段可以继续添加
            };
          } catch (error) {
            console.error(`获取关联信息失败(ID:${item.id}):`, error);
            return {
              ...item,
              roomName: "加载失败",
              seatNumber: "加载失败",
              userName: "加载失败",
            };
          }
        })
      );
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reviewForm = {
        id: row.id,
        userName: row.userName,
        roomName: row.roomName,
        seatNumber: row.seatNumber,
        approved: true,
        reason: row.reason,
      };
      this.reviewOpen = true;
    },
    /** 提交审核 */
    submitReview() {
      this.$refs["reviewForm"].validate((valid) => {
        if (valid) {
          reviewReservationAPI({
            id: this.reviewForm.id,
            approved: this.reviewForm.approved,
            reason: this.reviewForm.reason,
          })
            .then((response) => {
              this.$modal.msgSuccess("审核成功");
              this.reviewOpen = false;
              this.getList();
            })
            .catch((error) => {
              console.error("审核失败:", error);
              this.$modal.msgError("审核失败: " + (error.message || ""));
            });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id ? [row.id] : this.ids;
      this.$modal
        .confirm("确认删除选中的预约记录？")
        .then(() => {
          deleteReservationAPI(ids).then((response) => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          });
        })
        .catch(() => {});
    },
  },
};
</script>

<style scoped>
.el-tag {
  margin: 2px;
}
</style>
